// 核心配置参数
const selectors = [
  { selector: "#btn1", message: "点此【新增】数据！" },
  { selector: "#btn2", message: "小心【删除】数据！" },
  { selector: "#btn3", message: "可通过此按钮【修改】数据！" },
  { selector: "#btn4", message: "一键【完成】所有操作！" },
];

const guideModal = document.getElementById("guideModal");
const guideBox = document.getElementById("guideBox");
const guideMessage = document.getElementById("guideMessage");
const guidePrevBtn = document.getElementById("guidePrevBtn");
const guideNextBtn = document.getElementById("guideNextBtn");
let cloneNode = null;
let currNode = null;
let index = 0;
let show = true;

document.addEventListener("DOMContentLoaded", () => {
  genGuide();
});

// 页面内容发生变化时，重新计算位置
window.addEventListener("resize", () => genGuide(false));
window.addEventListener("scroll", () => genGuide(false));

guidePrevBtn.addEventListener("click", () => {
  changeStep(true);
});
guideNextBtn.addEventListener("click", () => {
  changeStep(false);
});

function changeStep(isPre) {
  isPre ? index-- : index++;
  currNode = null;
  genGuide();
}

function genGuide(hasChange = true) {
  // 前置操作
  cloneNode && guideModal.removeChild(cloneNode);

  // 所有指引完毕
  if (index > selectors.length - 1) {
    show = false;
    return;
  }

  // 获取目标节点信息
  currNode = currNode || document.querySelector(selectors[index].selector);
  const { x, y, width, height } = currNode.getBoundingClientRect();

  // 克隆节点
  cloneNode = hasChange ? currNode.cloneNode(true) : cloneNode;
  cloneNode.id = currNode.id + "_clone";
  cloneNode.style = `margin-left: ${x}px;margin-top: ${y}px;`; // 复制节点的偏移量

  // 指引相关
  if (guideBox) {
    const halfClientHeight = guideBox.clientHeight / 2;
    guideMessage.innerText = selectors[index].message;
    guideBox.style = `left:${x + width + 10}px; 
    top:${y <= halfClientHeight ? y : y - halfClientHeight + height / 2}px;`;

    guideModal.appendChild(cloneNode);
  }
}
